home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / rdflib / Literal.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  11.6 KB  |  365 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from rdflib.Identifier import Identifier
  5. from rdflib.URIRef import URIRef
  6. from rdflib.Namespace import Namespace
  7. from rdflib.exceptions import Error
  8. from datetime import date, time, datetime
  9. from time import strptime
  10. import base64
  11.  
  12. try:
  13.     from hashlib import md5
  14. except ImportError:
  15.     from md5 import md5
  16.  
  17. import logging
  18. _logger = logging.getLogger(__name__)
  19.  
  20. class Literal(Identifier):
  21.     '''
  22.     RDF Literal: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal
  23.  
  24.     >>> Literal(1).toPython()
  25.     1L
  26.     >>> cmp(Literal("adsf"), 1)
  27.     1
  28.     >>> lit2006 = Literal(\'2006-01-01\',datatype=_XSD_NS.date)
  29.     >>> lit2006.toPython()
  30.     datetime.date(2006, 1, 1)
  31.     >>> lit2006 < Literal(\'2007-01-01\',datatype=_XSD_NS.date)
  32.     True
  33.     >>> oneInt     = Literal(1)
  34.     >>> twoInt     = Literal(2)
  35.     >>> twoInt < oneInt
  36.     False
  37.     >>> Literal(\'1\') < Literal(1)
  38.     False
  39.     >>> Literal(\'1\') < Literal(\'1\')
  40.     False
  41.     >>> Literal(1) < Literal(\'1\')
  42.     True
  43.     >>> Literal(1) < Literal(2.0)
  44.     True
  45.     >>> Literal(1) < URIRef(\'foo\')
  46.     True
  47.     >>> Literal(1) < 2.0
  48.     True
  49.     >>> Literal(1) < object  
  50.     True
  51.     >>> lit2006 < "2007"
  52.     True
  53.     >>> "2005" < lit2006
  54.     True
  55.     '''
  56.     __slots__ = ('language', 'datatype', '_cmp_value')
  57.     
  58.     def __new__(cls, value, lang = None, datatype = None):
  59.         if datatype:
  60.             lang = None
  61.         else:
  62.             (value, datatype) = _castPythonToLiteral(value)
  63.             if datatype:
  64.                 lang = None
  65.             
  66.         if datatype:
  67.             datatype = URIRef(datatype)
  68.         
  69.         
  70.         try:
  71.             inst = unicode.__new__(cls, value)
  72.         except UnicodeDecodeError:
  73.             inst = unicode.__new__(cls, value, 'utf-8')
  74.  
  75.         inst.language = lang
  76.         inst.datatype = datatype
  77.         inst._cmp_value = inst._toCompareValue()
  78.         return inst
  79.  
  80.     
  81.     def __reduce__(self):
  82.         return (Literal, (unicode(self), self.language, self.datatype))
  83.  
  84.     
  85.     def __getstate__(self):
  86.         return (None, dict(language = self.language, datatype = self.datatype))
  87.  
  88.     
  89.     def __setstate__(self, arg):
  90.         (_, d) = arg
  91.         self.language = d['language']
  92.         self.datatype = d['datatype']
  93.  
  94.     
  95.     def __add__(self, val):
  96.         '''
  97.         >>> Literal(1) + 1
  98.         2L
  99.         >>> Literal("1") + "1"
  100.         rdflib.Literal(\'11\', language=None, datatype=None)
  101.         '''
  102.         py = self.toPython()
  103.         if isinstance(py, Literal):
  104.             s = super(Literal, self).__add__(val)
  105.             return Literal(s, self.language, self.datatype)
  106.         return py + val
  107.  
  108.     
  109.     def __lt__(self, other):
  110.         if other is None:
  111.             return False
  112.         
  113.         try:
  114.             return self._cmp_value < other
  115.         except TypeError:
  116.             other is None
  117.             te = other is None
  118.             return unicode(self._cmp_value) < other
  119.  
  120.  
  121.     
  122.     def __le__(self, other):
  123.         if other is None:
  124.             return False
  125.         if self == other:
  126.             return True
  127.         return self < other
  128.  
  129.     
  130.     def __gt__(self, other):
  131.         if other is None:
  132.             return True
  133.         
  134.         try:
  135.             return self._cmp_value > other
  136.         except TypeError:
  137.             other is None
  138.             te = other is None
  139.             return unicode(self._cmp_value) > other
  140.  
  141.  
  142.     
  143.     def __ge__(self, other):
  144.         if other is None:
  145.             return False
  146.         if self == other:
  147.             return True
  148.         return self > other
  149.  
  150.     
  151.     def __ne__(self, other):
  152.         """
  153.         Overriden to ensure property result for comparisons with None via !=.
  154.         Routes all other such != and <> comparisons to __eq__
  155.         
  156.         >>> Literal('') != None
  157.         True
  158.         >>> Literal('2') <> Literal('2')
  159.         False
  160.          
  161.         """
  162.         if other is None:
  163.             return True
  164.         return not self.__eq__(other)
  165.  
  166.     
  167.     def __eq__(self, other):
  168.         '''        
  169.         >>> f = URIRef("foo")
  170.         >>> f is None or f == \'\'
  171.         False
  172.         >>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo"))
  173.         True
  174.         >>> Literal("1", datatype=URIRef("foo")) == Literal("2", datatype=URIRef("foo"))
  175.         False
  176.         >>> Literal("1", datatype=URIRef("foo")) == "asdf"
  177.         False
  178.         >>> oneInt     = Literal(1)
  179.         >>> oneNoDtype = Literal(\'1\')
  180.         >>> oneInt == oneNoDtype
  181.         False
  182.         >>> Literal("1",_XSD_NS[u\'string\']) == Literal("1",_XSD_NS[u\'string\']) 
  183.         True
  184.         >>> Literal("one",lang="en") == Literal("one",lang="en")
  185.         True
  186.         >>> Literal("hast",lang=\'en\') == Literal("hast",lang=\'de\')
  187.         False
  188.         >>> oneInt == Literal(1)
  189.         True
  190.         >>> oneFloat   = Literal(1.0)
  191.         >>> oneInt == oneFloat
  192.         True
  193.         >>> oneInt == 1
  194.         True
  195.         '''
  196.         if other is None:
  197.             return False
  198.         return self._cmp_value == other
  199.  
  200.     
  201.     def n3(self):
  202.         language = self.language
  203.         datatype = self.datatype
  204.         if self.find('\n') != -1:
  205.             encoded = self.replace('\\', '\\\\')
  206.             if self.find('"""') != -1:
  207.                 encoded = encoded.replace('"""', '\\"""')
  208.             
  209.             if encoded.endswith('"'):
  210.                 encoded = encoded[:-1] + '\\"'
  211.             
  212.             encoded = '"""%s"""' % encoded
  213.         else:
  214.             encoded = '"%s"' % self.replace('\n', '\\n').replace('\\', '\\\\').replace('"', '\\"')
  215.         if language:
  216.             if datatype:
  217.                 return '%s@%s^^<%s>' % (encoded, language, datatype)
  218.             return '%s@%s' % (encoded, language)
  219.         language
  220.         if datatype:
  221.             return '%s^^<%s>' % (encoded, datatype)
  222.         return '%s' % encoded
  223.  
  224.     
  225.     def __str__(self):
  226.         return self.encode('unicode-escape')
  227.  
  228.     
  229.     def __repr__(self):
  230.         return "rdflib.Literal('%s', language=%s, datatype=%s)" % (str(self), repr(self.language), repr(self.datatype))
  231.  
  232.     
  233.     def toPython(self):
  234.         '''
  235.         Returns an appropriate python datatype derived from this RDF Literal
  236.         '''
  237.         convFunc = _toPythonMapping.get(self.datatype, None)
  238.         if convFunc:
  239.             rt = convFunc(self)
  240.         else:
  241.             rt = self
  242.         return rt
  243.  
  244.     
  245.     def _toCompareValue(self):
  246.         
  247.         try:
  248.             rt = self.toPython()
  249.         except Exception:
  250.             e = None
  251.             _logger.warning('could not convert %s to a Python datatype' % repr(self))
  252.             rt = self
  253.  
  254.         if rt is self:
  255.             if self.language is None and self.datatype is None:
  256.                 return unicode(rt)
  257.             return (unicode(rt), rt.datatype, rt.language)
  258.         rt is self
  259.         return rt
  260.  
  261.     
  262.     def md5_term_hash(self):
  263.         d = md5(str(self))
  264.         d.update('L')
  265.         return d.hexdigest()
  266.  
  267.  
  268. _XSD_NS = Namespace(u'http://www.w3.org/2001/XMLSchema#')
  269.  
  270. def _castPythonToLiteral(obj):
  271.     for castFunc, dType in _PythonToXSD.items():
  272.         if isinstance(obj, pType):
  273.             if castFunc:
  274.                 return (castFunc(obj), dType)
  275.             if dType:
  276.                 return (obj, dType)
  277.             return (obj, None)
  278.         isinstance(obj, pType)
  279.     
  280.     return (obj, None)
  281.  
  282. _PythonToXSD = {
  283.     basestring: (None, None),
  284.     float: (None, _XSD_NS[u'float']),
  285.     int: (None, _XSD_NS[u'int']),
  286.     long: (None, _XSD_NS[u'long']),
  287.     bool: (None, _XSD_NS[u'boolean']),
  288.     date: ((lambda i: i.isoformat()), _XSD_NS[u'date']),
  289.     time: ((lambda i: i.isoformat()), _XSD_NS[u'time']),
  290.     datetime: ((lambda i: i.isoformat()), _XSD_NS[u'dateTime']) }
  291.  
  292. def _strToTime(v):
  293.     return strptime(v, '%H:%M:%S')
  294.  
  295.  
  296. def _strToDate(v):
  297.     tstr = strptime(v, '%Y-%m-%d')
  298.     return date(tstr.tm_year, tstr.tm_mon, tstr.tm_mday)
  299.  
  300.  
  301. def _strToDateTime(v):
  302.     '''
  303.     Attempt to cast to datetime, or just return the string (otherwise)
  304.     '''
  305.     
  306.     try:
  307.         tstr = strptime(v, '%Y-%m-%dT%H:%M:%S')
  308.     except:
  309.         
  310.         try:
  311.             tstr = strptime(v, '%Y-%m-%dT%H:%M:%SZ')
  312.         try:
  313.             tstr = strptime(v, '%Y-%m-%dT%H:%M:%S%Z')
  314.         return v
  315.  
  316.     
  317.  
  318.     return datetime(tstr.tm_year, tstr.tm_mon, tstr.tm_mday, tstr.tm_hour, tstr.tm_min, tstr.tm_sec)
  319.  
  320. XSDToPython = {
  321.     _XSD_NS[u'time']: _strToTime,
  322.     _XSD_NS[u'date']: _strToDate,
  323.     _XSD_NS[u'dateTime']: _strToDateTime,
  324.     _XSD_NS[u'string']: None,
  325.     _XSD_NS[u'normalizedString']: None,
  326.     _XSD_NS[u'token']: None,
  327.     _XSD_NS[u'language']: None,
  328.     _XSD_NS[u'boolean']: (lambda i: i.lower() in ('1', 'true')),
  329.     _XSD_NS[u'decimal']: float,
  330.     _XSD_NS[u'integer']: long,
  331.     _XSD_NS[u'nonPositiveInteger']: int,
  332.     _XSD_NS[u'long']: long,
  333.     _XSD_NS[u'nonNegativeInteger']: int,
  334.     _XSD_NS[u'negativeInteger']: int,
  335.     _XSD_NS[u'int']: long,
  336.     _XSD_NS[u'unsignedLong']: long,
  337.     _XSD_NS[u'positiveInteger']: int,
  338.     _XSD_NS[u'short']: int,
  339.     _XSD_NS[u'unsignedInt']: long,
  340.     _XSD_NS[u'byte']: int,
  341.     _XSD_NS[u'unsignedShort']: int,
  342.     _XSD_NS[u'unsignedByte']: int,
  343.     _XSD_NS[u'float']: float,
  344.     _XSD_NS[u'double']: float,
  345.     _XSD_NS[u'base64Binary']: base64.decodestring,
  346.     _XSD_NS[u'anyURI']: None }
  347. _toPythonMapping = { }
  348. _toPythonMapping.update(XSDToPython)
  349.  
  350. def bind(datatype, conversion_function):
  351.     '''bind a datatype to a function for converting it into a Python instance.'''
  352.     if datatype in _toPythonMapping:
  353.         _logger.warning("datatype '%s' was already bound. Rebinding." % datatype)
  354.     
  355.     _toPythonMapping[datatype] = conversion_function
  356.  
  357.  
  358. def test():
  359.     import doctest
  360.     doctest.testmod()
  361.  
  362. if __name__ == '__main__':
  363.     test()
  364.  
  365.